package main

import (
	"fmt"
	"github.com/urfave/cli/v2"
	"log"
	"os"
	"sync"
	"time"
)

var (
	l     sync.Mutex
	once  sync.Once
	ready = make(chan bool)
)

func main() {

	//go build goFileName 编译后输入命令  ./goRunFile --parameter1=xxx --parameter2=xxx --parameter3=x funcName
	app := &cli.App{
		Name: "Go Commands",
		Flags: []cli.Flag{
			&cli.StringFlag{
				Name:  "parameter1",
				Usage: "参数1(string)",
			},
			&cli.StringFlag{
				Name:  "parameter2",
				Usage: "参数2(string)",
			},
			&cli.IntFlag{
				Name:  "parameter3",
				Usage: "参数3(int)",
			},
		},
		Before: func(context *cli.Context) error {
			go beforeAction()
			select {
			case <-ready:
			case <-time.After(10 * time.Second)://十秒超时
				panic("获取超时")
				return nil
			}
			return nil
		},
		After: func(context *cli.Context) error {
			fmt.Println("app After message...")
			return nil
		},
		Commands: []*cli.Command{
			{
				Name: "doingOne",
				Action: func(context *cli.Context) error {
					if err := doingOne(); err != nil {
						fmt.Println(err)
						return err
					}
					return nil
				},
			},
			{
				Name: "start",
				Action: func(context *cli.Context) error {
					fmt.Println("开始game")
					start()
					fmt.Printf("game结束,时间:%s\n", time.Now().Format("2006-01-02 15:04:05"))
					return nil
				},
			},
			{
				Name: "end",
				Action: func(context *cli.Context) error {
					fmt.Println("退出game")
					start()
					fmt.Printf("退出时间:%s\n", time.Now().Format("2006-01-02 15:04:05"))
					return nil
				},
			},
		},
	}

	app.Name = "go command"
	app.Usage = "this is go command template"
	if err := app.Run(os.Args); err != nil {
		return
	}
}

func beforeAction() {
	for {
		l.Lock()
		log.Println("before action")
		//业务逻辑
		//time.Sleep(10.*time.Second)
		l.Unlock()
		once.Do(func() {
			close(ready)
		},
		)
		time.Sleep(2 * time.Second)
	}
}

func doingOne() error {
	log.Println("dingOne")
	return nil
}

func start()  {
	log.Println("start...")
}
